/**
 * 
 */
package sopia.sg;

import java.util.Calendar;

import sopia.cmm.CommonFunct;
import sopia.cmm.Constant;
import sopia.conn.AccountAdapter;
import sopia.conn.CustomerSpinnerAdapter;
import sopia.conn.DBAdapter;
import sopia.conn.ExpenseAdapter;
import sopia.conn.ItemExpenseAdapter;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author tatsu@gmail.com
 *
 */
public class G005Activity extends Activity {
	
	private Button addItemExpensive_button ;
	private EditText itemName_edit ;
	private Spinner typeExpSpinner ;
	private EditText amountSpend_edit ;
	private Button datepicker_item_button ;
	private EditText comment_edit  ;
	private Spinner accSpinner ;
	
	private String valueTypeExpSelected;
	private String valueAccountSelected;
	
	private AccountAdapter accAdapter ;
	private ExpenseAdapter typeExpAdapter ;
	private ItemExpenseAdapter itemExpAdapter;

	private TextView unit_item;
	//save value input
	private static String itemNameSave = Constant.EMPTY_STRING;
	private static String typeExpSave ;
	private static String amountSpentSave = Constant.ZERO_VALUE;
	private static String dateItemSave = Constant.EMPTY_STRING;
	private static String commentSave = Constant.EMPTY_STRING;
	private static String useAccountSave;
	private static ArrayAdapter<CustomerSpinnerAdapter> adapterTypeExp;
	private static ArrayAdapter<CustomerSpinnerAdapter> adapterUseAcc;
//	private static String dateItem = Constant.EMPTY_STRING;
	//
	private int myYear, myMonth, myDay;
	private String dateSelected, dateToday;
	private Button datePickerButton;
	static final int ID_DATEPICKER = 0;
    private Button.OnClickListener datePickerButtonOnClickListener
	    = new Button.OnClickListener(){

	  @Override
	  public void onClick(View v) {
	   final Calendar c = Calendar.getInstance();
	   myYear = c.get(Calendar.YEAR);
	   myMonth = c.get(Calendar.MONTH);
	   myDay = c.get(Calendar.DAY_OF_MONTH);
	   showDialog(ID_DATEPICKER);
	  }
	   };
	 private DatePickerDialog.OnDateSetListener myDateSetListener
	  = new DatePickerDialog.OnDateSetListener(){
	   @Override
	   public void onDateSet(DatePicker view, int year, 
	     int monthOfYear, int dayOfMonth) {
	    dateSelected =String.valueOf(year) + "/" + String.valueOf(monthOfYear + 1) + "/" + String.valueOf(dayOfMonth);
	    dateItemSave = dateSelected;
	    datePickerButton.setText(dateSelected);
	   } 
	 };
	/**
	 * 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.g005_layout);
		datePickerButton = (Button)findViewById(R.id.datepicker_item_button);
        datePickerButton.setOnClickListener(datePickerButtonOnClickListener);
     
        init();
	}


   
	private void init() {
		unit_item = (TextView) findViewById(R.id.unit_item);
		unit_item.setText(G001Activity.curUnitCurrency != null ?
				G001Activity.curUnitCurrency : G003Activity.valueCurrencySelected );
		//init date
	    final Calendar cl = Calendar.getInstance();
	    myYear = cl.get(Calendar.YEAR);
	    myMonth = cl.get(Calendar.MONTH);
	    myDay = cl.get(Calendar.DAY_OF_MONTH);
	    
	    dateToday =String.valueOf(myYear) + "/" + String.valueOf(myMonth + 1) + "/" + String.valueOf(myDay);
	    if(Constant.EMPTY_STRING.equals(dateItemSave)){
	    	dateItemSave = dateToday;
		}
	    datePickerButton.setText(dateToday);
		//init spinner
	    initTypeExpSpinner(G001Activity.curNameAccount);
	    initAccountSpinner();
	    
		int posAcc = CommonFunct.getIndexFromElement(adapterUseAcc, G001Activity.curNameAccount);
		//set the old according to value
		accSpinner.setSelection(posAcc);
		
		// forward add type expensive
		final Button forward_addTypeExpensive_button = (Button) findViewById(R.id.forward_addTypeExpensive_button);
		forward_addTypeExpensive_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent i = new Intent(G005Activity.this, G004Activity.class);
				i.putExtra("ID", "G005");
				i.putExtra("PlugID", "G005");
				//save value before forward to screen
				itemNameSave = itemName_edit.getText().toString().trim();
				typeExpSave = valueTypeExpSelected;
				amountSpentSave = amountSpend_edit.getText().toString();
				dateItemSave = datepicker_item_button.getText().toString();
				commentSave = comment_edit.getText().toString();
				useAccountSave = valueAccountSelected ;
				//
				startActivity(i);
				finish();
			}
		});
	    // forward add Account 
		final Button forward_addAccount_button = (Button) findViewById(R.id.forward_addAccount_button);
		forward_addAccount_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(G005Activity.this, G003Activity.class);
				i.putExtra("ID", "G005");
				startActivity(i);
				finish();
			}
		});
		//
		/*START cast action click button addItemExpensive_button*/ 
		addItemExpensive_button = (Button) findViewById(R.id.addItemExpensive_button);
		itemName_edit = (EditText) findViewById(R.id.itemName_edit);
		//typeExpSpinner
		valueTypeExpSelected = Constant.EMPTY_STRING;
		typeExpSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				CustomerSpinnerAdapter typeExp = (CustomerSpinnerAdapter) typeExpSpinner.getItemAtPosition(position);
				valueTypeExpSelected = typeExp.getValue();
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		
		
		amountSpend_edit = (EditText) findViewById(R.id.amountSpend_edit);
		datepicker_item_button = (Button) findViewById(R.id.datepicker_item_button);
		comment_edit = (EditText) findViewById(R.id.comment_edit);
		//accSpinner 
		
		
		valueAccountSelected = Constant.EMPTY_STRING;
		accSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				CustomerSpinnerAdapter account = (CustomerSpinnerAdapter) accSpinner.getItemAtPosition(position);
				valueAccountSelected = account.getValue();
				initTypeExpSpinner(valueAccountSelected);
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		addItemExpensive_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(checkAmountAvailable()){
					insertItemExpense(itemName_edit.getText().toString().trim()
								 ,valueTypeExpSelected,amountSpend_edit.getText().toString()
								 , datepicker_item_button.getText().toString()
								 , comment_edit.getText().toString(),valueAccountSelected);
				}else{
					showErrorMessage();
				}
			}
		});
		/*END cast action click button addItemExpensive_button*/ 
		setOldValueScreen();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	  //Handle the back button
	  if (keyCode == KeyEvent.KEYCODE_BACK) {
		  	 backToPreviousScreen();
			 removeStaticValue();
	    return true;
	  }

	  return super.onKeyDown(keyCode, event);
	} 
   
	private void showErrorMessage(){
		if(CommonFunct.isNullOrEmpty(amountSpend_edit.getText().toString())){
			Toast.makeText(this,"Please input value Amount" , Toast.LENGTH_LONG).show();
			amountSpend_edit.selectAll();
			amountSpend_edit.requestFocus();
			return;
		}else{
			double amount = Double.parseDouble(amountSpend_edit.getText().toString());
			if(0 == amount){
					Toast.makeText(this,"Please input value Amount more than zero" , Toast.LENGTH_LONG).show();
					amountSpend_edit.selectAll();
					amountSpend_edit.requestFocus();
			}else {	
				String contentMessage =CommonFunct.join("With amount [",
						String.valueOf(Double.parseDouble(amountSpend_edit.getText().toString())),
						" " , G001Activity.curUnitCurrency,
						"] that Type Expense name [",
						valueTypeExpSelected,
						"] not enough to create this item expense. \n Plz try again input value less than it.");
				Toast.makeText(this,contentMessage , Toast.LENGTH_LONG).show();
				amountSpend_edit.selectAll();
				amountSpend_edit.requestFocus();
			}
		}
	}
	private void setOldValueScreen() {
		itemName_edit.setText(itemNameSave);	
		int spinnerPosition1 = CommonFunct.getIndexFromElement(adapterTypeExp, typeExpSave);
		//set the old according to value
		typeExpSpinner.setSelection(spinnerPosition1);
		
		amountSpend_edit.setText(amountSpentSave);	
		datepicker_item_button.setText(dateItemSave);	
		comment_edit.setText(commentSave);	
		
		if(CommonFunct.isNullOrEmpty(useAccountSave)){
			useAccountSave = G001Activity.curNameAccount;
		}
		int spinnerPosition2 = CommonFunct.getIndexFromElement(adapterUseAcc, useAccountSave);
		//set the old according to value
		accSpinner.setSelection(spinnerPosition2);
		
	}
	private void removeStaticValue(){
		itemNameSave = Constant.EMPTY_STRING;
		amountSpentSave = Constant.ZERO_VALUE;
		commentSave = Constant.EMPTY_STRING;
		datepicker_item_button.setText(dateToday);
		typeExpSpinner.setSelection(0);
		accSpinner.setSelection(0);
		
	}
	private boolean checkAmountAvailable(){
		String amountItem =amountSpend_edit.getText().toString();
		try {
			if(CommonFunct.isNullOrEmpty(amountItem)){
					return false;
			}
			double amountInput  = Double.parseDouble(amountItem);
			double amountUse = this.getAmountUsed();
			double totalAmount = this.getTotalAmount();
			if(totalAmount - amountUse >= amountInput){
				return true;
			}else{
				return false;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return false;
	}
	private double getTotalAmount(){
		double amount = 0 ; 
		try {
			//get data
			typeExpAdapter = new ExpenseAdapter(this);	
			Cursor cur = typeExpAdapter.getAmountByTypeExpenseAccount(valueTypeExpSelected,valueAccountSelected);
			if (cur.moveToFirst()) {
		         do {
		        	 amount += cur.getDouble(0);
		         } while (cur.moveToNext());
		      }
		      if (cur != null && !cur.isClosed()) {
		    	  cur.close();
		      }
		      typeExpAdapter.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return amount;
	}
	private double getAmountUsed(){
		double amount = 0 ; 
		try {
			//get data
			itemExpAdapter = new ItemExpenseAdapter(this);	
			Cursor cur = itemExpAdapter.getAmountByTypeExpenseAccount(valueTypeExpSelected,valueAccountSelected);
			if (cur.moveToFirst()) {
		         do {
		        	 amount += cur.getDouble(0);
		         } while (cur.moveToNext());
		      }
		      if (cur != null && !cur.isClosed()) {
		    	  cur.close();
		      }
		      itemExpAdapter.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return amount;
	}
	
	protected void insertItemExpense(String itemName,
			String typeExpense, String amountItemExp, String dateItemExp,
			String commentItem, String accountName) {
		try {
			itemExpAdapter = new ItemExpenseAdapter(this);	
			itemExpAdapter.beginTransaction();
			if(CommonFunct.isNullOrEmpty(itemName)){
				itemName = null;
				Toast.makeText(this,"Please input [Item name]!" , Toast.LENGTH_LONG).show();
				itemName_edit.setFocusable(true);
				return;
			}
			if(CommonFunct.isNullOrEmpty(amountItemExp)){
				Toast.makeText(this,"Please input value Amount" , Toast.LENGTH_LONG).show();
				amountSpend_edit.selectAll();
				amountSpend_edit.requestFocus();
				return;
			}else{
				double amount = Double.parseDouble(amountItemExp);
				if(0 == amount){
					Toast.makeText(this,"Please input value Amount more than zero" , Toast.LENGTH_LONG).show();
					amountSpend_edit.selectAll();
					amountSpend_edit.requestFocus();
					return;
				}
			}
			
			if(CommonFunct.isNullOrEmpty(typeExpense)){
				Toast.makeText(this,"Please create Type Expense" , Toast.LENGTH_LONG).show();
				typeExpSpinner.requestFocus();
				return;
			}
			
			Long id = itemExpAdapter.insertItemExpense(itemName, typeExpense, 
					amountItemExp, dateItemExp, commentItem, accountName);
		
			//the row ID of the newly inserted row, or -1 if an error occurred 
			String contentMessage = "Item Expense [ "+ itemName;
			if(id < 0){			
				contentMessage += "] really exist your database.";
				Toast.makeText(this,contentMessage , Toast.LENGTH_LONG).show();
				itemName_edit.selectAll();
			}else{
				contentMessage += "] was added.";				
				backToPreviousScreen();
				Toast.makeText(this, contentMessage , Toast.LENGTH_LONG).show();
			}
			itemExpAdapter.setTransactionSuccessful();
		} catch (Exception e) {
			Log.e("insertTypeExpense", e.toString());
		}finally {
			itemExpAdapter.endTransaction();
			itemExpAdapter.close();
		}
		
	}
	private void backToPreviousScreen() {
		Intent i = new Intent(G005Activity.this, G002Activity.class);
		i.putExtra("ID", "G005");
		startActivity(i);
		finish();
	}
	private void initTypeExpSpinner(String nameAccount) {
		try {
			typeExpSpinner = (Spinner) findViewById(R.id.typeExpensive_combobox);
//			//get data
			typeExpAdapter = new ExpenseAdapter(this);	
			System.err.println("=================="+ nameAccount);
			Cursor cur = typeExpAdapter.getAllExpenseByAccount(nameAccount);
			
			Log.d(String.valueOf(cur.getCount()), "initTypeExpSpinner");
			typeExpAdapter.close();
//			//set data
			final CustomerSpinnerAdapter[] items = CommonFunct.getSpinnerAdapter(cur);
			adapterTypeExp = new ArrayAdapter<CustomerSpinnerAdapter>(
					this, android.R.layout.simple_spinner_item, items);
			adapterTypeExp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			typeExpSpinner.setAdapter(adapterTypeExp);
			if (cur != null && !cur.isClosed()) {
		      cur.close();
		    }
		} catch (Exception e) {
			Log.e("G005-initTypeExpSpinner", e.toString());
		}
		
	}



	private void initAccountSpinner() {
		try {
			accSpinner = (Spinner) findViewById(R.id.typeAccount_combobox);
//			//get data
			accAdapter = new AccountAdapter(this);	
			Cursor cur = accAdapter.getAllAccountByCurrency(G001Activity.curUnitCurrency);
			Log.d(String.valueOf(cur.getCount()), "test");
			accAdapter.close();
//			//set data
			final CustomerSpinnerAdapter[] items = CommonFunct.getSpinnerAdapter(cur);
			adapterUseAcc = new ArrayAdapter<CustomerSpinnerAdapter>(
					this, android.R.layout.simple_spinner_item, items);
			adapterUseAcc.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			accSpinner.setAdapter(adapterUseAcc);
			if (cur != null && !cur.isClosed()) {
		      cur.close();
		    }
		} catch (Exception e) {
			Log.e("G005-initAccountSpinner", e.toString());
		}
	}



	@Override
	 protected Dialog onCreateDialog(int id) {
	  // TODO Auto-generated method stub
	  switch(id){
	   case ID_DATEPICKER:
	    return new DatePickerDialog(this,
	      myDateSetListener,
	      myYear, myMonth, myDay);
	   default:
	    return null;
	  }
	 }
}
